//
//  CustomTabBarCtrl.m
//
//  Created by Northwan on 15-4-12.
//  Copyright (c) 2015年 . All rights reserved.
//

#import "CustomTabBarCtrl.h"
#import "YSRecommendCtrl.h"
#import "YSClubCtrl.h"
#import "YSMineCtrl.h"
#import "YSLoginCtrl.h"
#import "YSCategorieCtrl.h"
#import "YSModifyInfoCtrl.h"

@interface CustomTabBarCtrl ()<UITabBarControllerDelegate>
@property (nonatomic, weak) UIViewController *lastSelectedViewContoller;
@property (nonatomic, strong) YSRecommendCtrl *home;
@property (nonatomic, strong) YSClubCtrl *club;
@property (nonatomic, strong) YSCategorieCtrl *categories;
@property (nonatomic, strong) YSMineCtrl *mine;

@end

@implementation CustomTabBarCtrl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setDelegate:self];
    //设置穿透效果
    CGRect frame = CGRectMake(0, 0, SCREENW, BottomTabarH);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    UIColor *color = [[UIColor alloc] initWithWhite:1.0 alpha:0.8];
    v.backgroundColor = color;
    [self.tabBar insertSubview:v atIndex:0];
    self.tabBar.opaque = YES;
    
    //首页
    _home = [[YSRecommendCtrl alloc]init];
    [self addOneChlildVc:_home title:@"悦食家" imageName:@"tabar_home_normal" selectedImageName:@"tabar_home_press" index:0];
    
    //俱乐部
    _club = [[YSClubCtrl alloc]init];
    [self addOneChlildVc:_club title:@"兴趣小组" imageName:@"tabar_club_normal" selectedImageName:@"tabar_club_press"index:1];
    
    //分类
    _categories = [[YSCategorieCtrl alloc]init];
    [self addOneChlildVc:_categories title:@"分类" imageName:@"tabar_category_normal" selectedImageName:@"tabar_category_press"index:2];
    
    //我
    _mine = [[YSMineCtrl alloc]init];
    [self addOneChlildVc:_mine title:@"我" imageName:@"tabar_mine_normal" selectedImageName:@"tabar_mine_press"index:3];
    
    [self registNortif];
}

-(void)registNortif{
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(identifierTimeOut)name:kLoginTimeOutNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toClubCtrl:)name:kToClubPageNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toHomeCtrl:)name:kToHomePageNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toCategoryCtrl:)name:kToCategoryPageNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toOtherCtrl:)name:kToOtherPageNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(toModifyInfoCtrl:) name:kRegistFinishToModifyInfoNortif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(dealNewMessageBadge:) name:kDealNewMessageBadgeNortif object:nil];
}

#pragma - 身份过期回调
-(void)identifierTimeOut{
    //身份过期,清除本地缓存的用户数据，弹出登陆页面
    [Utils clearExitInfo];
    [Utils showLoginCtrl:_home];
//     CustomNavigationCtrl *nav = [[CustomNavigationCtrl alloc]initWithRootViewController:[YSLoginCtrl new]];
//    [self presentViewController:nav animated:YES completion:nil];
    [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
}

#pragma - 跳转到俱乐部
-(void)toClubCtrl:(NSNotification *)nortif{
    if (_club) {
        [self setSelectedClass:[YSClubCtrl class]];
        [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
    }
}

#pragma - 跳转到分类
-(void)toCategoryCtrl:(NSNotification *)nortif{
    if (_categories) {
        [self setSelectedClass:[YSCategorieCtrl class]];
        [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
    }
}

#pragma - 跳转到首页
-(void)toHomeCtrl:(NSNotification *)nortif{
    if (_home) {
        [self setSelectedClass:[YSRecommendCtrl class]];
        [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
    }
}

#pragma - 跳转到其他页面，目前仅用于处理开屏页的跳转通知和推送的通知
-(void)toOtherCtrl:(NSNotification *)nortif{
   NSString *url =  [nortif object];
   [Utils dealUrlWithController:_home.navigationController.viewControllers.lastObject url:url fromWebView:NO];
}
#pragma - 跳转到修改信息页
-(void)toModifyInfoCtrl:(NSNotification *)nortif{
    if(_mine){
        [self.viewControllers makeObjectsPerformSelector:@selector(popToRootViewControllerAnimated:) withObject:[NSNumber numberWithBool:YES]];
        YSModifyInfoCtrl *ctrl = [YSModifyInfoCtrl new];
        [_mine.navigationController pushViewController:ctrl animated:YES];
    }
}
#pragma - 处理角标显示
-(void)dealNewMessageBadge:(NSNotification *)nortif{
    //TODO -
    
}

-(void)setSelectedClass:(Class)class{
    for (UINavigationController *ctrl in self.viewControllers) {
        if ([[ctrl.viewControllers firstObject] isKindOfClass:class]) {
            NSUInteger index = [self.viewControllers indexOfObject:ctrl];
            [self setSelectedIndex:index];
            break;
        }
    }
}

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UINavigationController *)viewController{
    UIViewController *vc = [viewController.viewControllers firstObject];
    if ([vc isKindOfClass:[YSClubCtrl class]]) {
        if (self.lastSelectedViewContoller == vc) {
            
        }
    }
    self.lastSelectedViewContoller = vc;
}

/**
 *  执行tabBar点击按钮动画
 *
 *  @param tabBar
 *  @param item
 */
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSNumber *num = objc_getAssociatedObject(item, @"tabbarindex");
    
    NSInteger index = 0;
    for (UIView *childView in tabBar.subviews) {
        if ([childView isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (index == num.integerValue) {
                [self dealStatistics:num];
                for (UIView *barButtonChildView in childView.subviews) {
                    if ([barButtonChildView isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]){
                        barButtonChildView.transform = CGAffineTransformMakeScale(0.5, 0.5);
                        [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.2 initialSpringVelocity:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                            barButtonChildView.transform = CGAffineTransformIdentity;
                        } completion:nil];
                    }
                }
            }
            index ++;
        }
    }
}


/**
 *  处理tab点击埋点统计
 *
 *  @param index 角标
 */
- (void)dealStatistics:(NSNumber *)index{
    NSString *indexName = @"TabHome";
    switch (index.integerValue) {
        case 0:
            indexName = @"TabHome";
            break;
        case 1:
            indexName = @"TabClub";
            break;
        case 2:
            indexName = @"TabCategory";
            break;
        case 3:
            indexName = @"TabSelf";
            break;
        default:
            break;
    }
    [TalkingData trackEvent:[NSString stringWithFormat:@"%@",indexName]];
}

/**
 *  添加一个子控制器
 *
 *  @param childVc           子控制器对象
 *  @param title             标题
 *  @param imageName         图标
 *  @param selectedImageName 选中的图标
 */
- (void)addOneChlildVc:(UIViewController *)childVc title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName index:(NSInteger)index
{
    
    NSLog(@"%@",childVc.tabBarItem);
    objc_setAssociatedObject(childVc.tabBarItem, @"tabbarindex", [NSNumber numberWithInteger:index], OBJC_ASSOCIATION_RETAIN);
    // 设置标题
    // 相当于同时设置了tabBarItem.title和navigationItem.title
    childVc.title = title;
    
    // 设置图标
    childVc.tabBarItem.image = [UIImage imageNamed:imageName];
    
    // 设置选中的图标
    UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
    // 声明这张图片用原图(别渲染)
    selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVc.tabBarItem.selectedImage = selectedImage;
    //    childVc.tabBarItem.imageInsets = UIEdgeInsetsMake(2.5, 0, -2.5, 0);
    [childVc.tabBarItem setSelectedImage:selectedImage];
    // 设置tabBarItem的普通文字颜色
    NSMutableDictionary *textAttrs = [NSMutableDictionary dictionary];
    textAttrs[NSForegroundColorAttributeName] = TabarItemTextNormalColor;
    textAttrs[NSFontAttributeName] = [UIFont systemFontOfSize:10];
    [childVc.tabBarItem setTitleTextAttributes:textAttrs forState:UIControlStateNormal];
    
    // 设置tabBarItem的选中文字颜色
    NSMutableDictionary *selectedTextAttrs = [NSMutableDictionary dictionary];
    //此主题颜色需要修改
    selectedTextAttrs[NSForegroundColorAttributeName] = TabarItemTextHighlightedColor;
    [childVc.tabBarItem setTitleTextAttributes:selectedTextAttrs forState:UIControlStateSelected];
    
    // 添加为tabbar控制器的子控制器
    UINavigationController *nav = [[CustomNavigationCtrl alloc] initWithRootViewController:childVc];
    [self addChildViewController:nav];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
